/**
  * @file		Meter.c
  * @author		Krubkib
  * @version	V1.0.0
  * @date		October 19, 2013
  * @brief		Meter
  */
/* Includes ------------------------------------------------------------------*/
#include "Meter.h"
#
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
  * @brief		connect message
  * @param		None
  * @retval		None
  */

void Meter_Energy(uint8_t address)
{ uint16_t checksum;
 	uint8_t packet[51];
	int i;
	crcInit();
 	packet[0] = 0x3A;
 	packet[1] = address;
	packet[2] = SOH;
	packet[3] = add_parity('R');
	packet[4] = add_parity('2');
	packet[5] = add_parity(STX);
	packet[6] = add_parity('D');
	packet[7] = add_parity('7');
	packet[8] = add_parity('(');
	packet[9] = add_parity(')');
	packet[10] = add_parity(ETX);
	packet[11] = bcc_parity(packet,3,11);
	for(i=12;i<48;i++){
	packet[i] = 0x23;
  }
	checksum = crcFast(packet,48);
	packet[48] = crc_LO(checksum);
	packet[49] = crc_HI(checksum);
	packet[50] = ETX;	
	
	for(i=0;i<51;i++){
	UART_write(packet[i]);
	delay(250);
	}
}
uint8_t add_parity(uint8_t ch)
{ 	
	int i;
	int p = 0;
	for(i=0;i<7;i++){	 
		p +=  ((ch>>i)&(0x01));
		//printf("p = %d\n",p);
		}	
		if(p%2 != 0){
			ch |= (1<<7);
		}	
		return ch;
}
uint8_t rm_parity(uint8_t val)
{
	val &= ~(1<<7);
	return val;
}
uint8_t bcc_parity(uint8_t mea[], int start,int end)
{
	int i;
	uint8_t bcc = 0x00;
	for (i=start;i<end;i++){
	bcc  ^= mea[i];
	
   }
	return bcc;
}
uint8_t crc_LO(uint16_t packet)
{
	uint8_t crc = 0x00;
  crc = crc|packet;		
	return crc;
}
uint8_t crc_HI(uint16_t packet)
{
	uint8_t crc = 0x00;
	crc = crc|(packet>>8);
	return crc;
}



